package com.march.aspect;

import com.alibaba.fastjson.JSON;
import com.march.utils.GsonUtil;
import com.march.utils.IpUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author 
 * @date 2019/2/12
 * @time 14:03 日志切面
 * @discription
 **/
@Aspect
@Component
@SuppressWarnings("all")
@Slf4j
public class WebLogAspect {
    // 开始时间
    private long startTime = 0L;


    /**
     * Controller层切点
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RestController)")
    public void controllerAspect() {
    }

    /**
     * Controller层切点
     */
    @Pointcut("execution (* com.march.controller..* (..))")
    public void marchControllerAspect() {
    }
    /**
     * 在切点之前织入
     *
     * @param joinPoint
     * @throws Throwable
     */
//    @Before("controllerAspect()")
    @Before("marchControllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime = System.currentTimeMillis();
    }

    /**
     * @Description 获取注解中对方法的描述信息 用于Controller层注解
     * @date 2018年9月3日 上午12:01
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    if (method.isAnnotationPresent(ApiOperation.class)) {
                        ApiOperation log = method.getAnnotation(ApiOperation.class);
                        description = method.getAnnotation(ApiOperation.class).value();
                    }
                    break;
                }
            }
        }
        return description;
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
//    @Around("controllerAspect()")
    @Around("marchControllerAspect()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = IpUtil.getIpAddr(request);

        //获取用户请求方法的参数并序列化为JSON格式字符串
        String params = "";
        Object[] arguments = new Object[proceedingJoinPoint.getArgs().length];
        if (proceedingJoinPoint.getArgs() != null && proceedingJoinPoint.getArgs().length > 0) {
            for (int i = 0; i < proceedingJoinPoint.getArgs().length; i++) {
                //这里出现参数不能转换问题，想了半天最后发现里面有request对象不能被序列化
                //最后把这些对象过滤了。
//                params += JSON.toJSON(joinPoint.getArgs()[i]) + ";";
                if (proceedingJoinPoint.getArgs()[i] instanceof ServletRequest || proceedingJoinPoint.getArgs()[i] instanceof ServletResponse || proceedingJoinPoint.getArgs()[i] instanceof MultipartFile) {
                    //HttpServletRequest不能序列化，从入参里排除，否则报异常：java.lang.IllegalStateException:
                    // It is illegal to call this method if the current request is not in asynchronous mode
                    // (i.e. isAsyncStarted() returns false)
                    continue;
                }
                arguments[i] = proceedingJoinPoint.getArgs()[i];
            }
        }
        if (arguments != null && arguments.length > 0) {
            try {
                //这里有个很严重的问题，因为JSON序列化有问题，所以这里会报错，改为Google 的Gson类来转换即可
                params = GsonUtil.GsonString(arguments);
            } catch (Exception e) {
                params = arguments.toString();
            }
        } else {
            params = "";
        }
        UpmsLog upmsLog = new UpmsLog();
        Object result = null;
        upmsLog.setDescription(getControllerMethodDescription(proceedingJoinPoint));
        result = proceedingJoinPoint.proceed();

//        try{
//
//        }catch (Exception e){
//            StackTraceElement s= e.getStackTrace()[0];
//            log.error("异常代码类/方法/行数:" +proceedingJoinPoint.getTarget().getClass().getName()+"/"+s.getMethodName()+"/"+s.getLineNumber());
//            /*logger.info("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));*/
//            log.error("方法描述:" + upmsLog.getDescription());
////            logger.info("请求IP:" + ip);
//            log.error("请求参数:" + params);
//        }
        upmsLog.getDescription();
        upmsLog.setMethod((proceedingJoinPoint.getTarget().getClass().getName() + "." + proceedingJoinPoint.getSignature().getName()));
        upmsLog.setIp(IpUtil.getIpAddr(request));
        upmsLog.setStartTime(startTime);
        upmsLog.setUri(ObjectUtils.toString(request.getRequestURL()));
        upmsLog.setResult(JSON.toJSONString(result));
        upmsLog.setParameter(params);
        long endTime = System.currentTimeMillis() - startTime;
        upmsLog.setSpendTime((int) endTime);
        upmsLog.setUserAgent(request.getHeader("User-Agent"));
        log.info(upmsLog.getMethod() + ":入参日志：{}", params);
        log.info("请求方式：{}", request.getMethod());
        log.info("出参日志：{}", result);
        log.info("接口耗时：{}", endTime);
//        log.info("操作日志：{}", GsonUtil.GsonString(upmsLog));
        return result;
    }

}